package com.elight.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

/**
 * GSON 封装工具类
 * 
 * @author zhoujunwen
 * @date 2016-12-05
 */
public class GsonUtils {
	/**
	 * 转成json
	 * 
	 * @param object
	 * @return
	 */
	public static String objToJSON(Object object) {
		Gson gson = new Gson();
		return gson.toJson(object);
	}

	/**
	 * 转成bean
	 * 
	 * @param gsonString
	 * @param cls
	 * @return
	 */
	public static <T> T jsonToBean(String gsonString, Class<T> cls) {
		Gson gson = new Gson();
		return gson.fromJson(gsonString, cls);
	}

	/**
	 * 转成list 泛型在编译期类型被擦除导致报错
	 * 
	 * @param gsonString
	 * @param cls
	 * @return
	 */
	public static <T> List<T> gsonToList(String gsonString, Class<T> cls) {
		List<T> mList = new ArrayList<T>();
		Gson gson = new Gson();
		JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
		for (JsonElement elem : array) {
			mList.add(gson.fromJson(elem, cls));
		}
		return mList;
	}

	/**
	 * 转成list 解决泛型问题
	 * 
	 * @param json
	 * @param cls
	 * @param <T>
	 * @return
	 */
	public <T> List<T> jsonToList(String json, Class<T> cls) {
		Gson gson = new Gson();
		List<T> list = new ArrayList<T>();
		JsonArray array = new JsonParser().parse(json).getAsJsonArray();
		for (final JsonElement elem : array) {
			list.add(gson.fromJson(elem, cls));
		}
		return list;
	}

	/**
	 * 转成list中有map的
	 * 
	 * @param gsonString
	 * @return
	 */
	public static <T> List<Map<String, T>> gsonToListMaps(String gsonString) {
		List<Map<String, T>> list = null;
		Gson gson = new Gson();
		list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {
		}.getType());
		return list;
	}

	/**
	 * 转成map的
	 * 
	 * @param gsonString
	 * @return
	 */
	public static <T> Map<String, T> gsonToMaps(String gsonString) {
		Map<String, T> map = null;
		Gson gson = new Gson();
		map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
		}.getType());
		return map;
	}
}
